package cn.bisoft.java.util.security;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.Signature;

import cn.bisoft.java.util.common.StringUtil;

import au.net.aba.crypto.provider.ABAProvider;
import au.net.aba.crypto.provider.RSAPrivKeyCrt;
import au.net.aba.crypto.provider.RSAPubKey;

/**
 * RSA ǩ��.
 */
public class RSAUtil {

	/** ˽Կ(�ֽ�16���Ʊ���) */
	private String priKey;

	/** ��Կ(�ֽ�16���Ʊ���) */
	private String pubKey;

	/** ���˽Կ�͹�Կ */
	public boolean generateKeys() {

		PublicKey keyPub;
		PrivateKey keyPri;
		SecureRandom rand;

		Security.addProvider(new ABAProvider());

		rand = new SecureRandom();

		rand.setSeed(System.currentTimeMillis());

		try {
			KeyPairGenerator fact;
			KeyPair keyPair;

			fact = KeyPairGenerator.getInstance("RSA");

			fact.initialize(1024, rand);

			keyPair = fact.generateKeyPair();

			keyPub = keyPair.getPublic();

			keyPri = keyPair.getPrivate();

			pubKey = StringUtil.bytesToHexStr(keyPub.getEncoded());

			priKey = StringUtil.bytesToHexStr(keyPri.getEncoded());
		} catch (Exception e) {
			System.err.println(e);
			e.printStackTrace(System.err);
			System.exit(1);
			return false;
		}
		return true;
	}

	/** ǩ��,ʹ��˽Կ��������, �õ����� */
	public String generateSigature(String src) {
		try {
			Security.addProvider(new ABAProvider());
			Signature sigEng = Signature.getInstance("MD5withRSA");

			byte[] pribyte = StringUtil.hexStrToBytes(priKey.trim());
			sigEng.initSign(new RSAPrivKeyCrt(pribyte));
			sigEng.update(src.getBytes());

			byte[] signature = sigEng.sign();
			return StringUtil.bytesToHexStr(signature);
		} catch (Exception e) {
			System.err.println(e);
			e.printStackTrace(System.err);
			return null;
		}
	}

	/** ��֤ǩ��, ʹ�ù�Կ����ǩ��,�������ıȽ� */
	public boolean verifySigature(String sign, String src) {
		try {
			Security.addProvider(new ABAProvider());
			Signature sigEng = Signature.getInstance("MD5withRSA");

			byte[] pubbyte = StringUtil.hexStrToBytes(pubKey.trim());
			sigEng.initVerify(new RSAPubKey(pubbyte));
			sigEng.update(src.getBytes());

			byte[] sign1 = StringUtil.hexStrToBytes(sign);
			if (sigEng.verify(sign1)) {
				return true;
			} else {
				return false;
			}

		} catch (Exception e) {
			System.err.println(e);
			e.printStackTrace(System.err);
			return false;
		}
	}
	
	public String getPublicKey() {
		return pubKey;
	}

	public String getPrivateKey() {
		return priKey;
	}

	public void setPublicKey(String pkey) {
		pubKey = pkey;
	}

	public void setPrivateKey(String pkey) {
		priKey = pkey;
	}

}
